package cn.dankal.flyaudio.oss.view;

import android.app.Activity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.View;
import android.widget.ImageView;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSAuthCredentialsProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.dankal.basiclib.base.activity.BaseActivity;
import cn.dankal.basiclib.common.camera.CamerImageBean;
import cn.dankal.basiclib.common.qiniu.UploadListener;
import cn.dankal.basiclib.common.upload.ali.AliOssService;
import cn.dankal.basiclib.common.upload.ali.AliUIDisplayer;
import cn.dankal.basiclib.util.DisplayHelper;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.basiclib.widget.FullyGridLayoutManager;
import cn.dankal.flyaudio.R;
import cn.dankal.flyaudio.current.post.Glide4Engine;
import cn.dankal.basiclib.common.upload.ali.Config;
import cn.dankal.flyaudio.personal.setting.FeedbackPicAdapter;


public class AliUploadActivity extends BaseActivity implements FeedbackPicAdapter.OnAddPicClickListener {

    //负责所有的界面更新
    private AliUIDisplayer mUIDisplayer;
    //上传的资源路径
    protected List<Uri> elements = new ArrayList<>();
    //上传后的图片路径
    protected List<String> finalKeys = new ArrayList<>();
    //OSS的上传下载
    protected AliOssService mService;
    private String objectName;
    private static final int RESULT_LOAD_IMAGE = 1;
    protected FeedbackPicAdapter mAdapter;
    @BindView(R.id.rv_pic)
    RecyclerView rvPic;
    private int count;//图片数量
    public int maxCount = 9;
    protected int type = 0;//0纯文本 1图片 2视频
    protected String suffix = ".png";
    public int REQUEST_CODE_CHOOSE = 200;

    @Override
    protected int getLayoutId() {
        return R.layout.my_main;
    }


    @Override
    protected void initComponents() {
        final ImageView imageView = findViewById(R.id.imageView);

        mUIDisplayer = new AliUIDisplayer(imageView, this, new UploadListener() {
            @Override
            public void onSucess(String filepath, String key) {
                count++;
                if (count == elements.size()) {
                    count = 0;
                    dismissLoadingDialog();
                    uploadComplete();
                    mUIDisplayer.uploadCompleteDialog();
                }
            }

            @Override
            public void onUpload(double percent) {
//                showLoadingDialog();
            }

            @Override
            public void onError(String string) {

            }
        });
        mService = initOSS(Config.OSS_ENDPOINT, mUIDisplayer);
        //从系统相册选择图片
//        final Button select = findViewById(R.id.select);
//        select.setOnClickListener(bg_card_details_1 -> {
//
//            Intent i = new Intent(
//                    Intent.ACTION_PICK,
//                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//
//            startActivityForResult(i, RESULT_LOAD_IMAGE);
//
//        });


        mAdapter = new FeedbackPicAdapter(this, this);
        //rvPic.setHasFixedSize(true);
        rvPic.setNestedScrollingEnabled(false);
        rvPic.setLayoutManager(new FullyGridLayoutManager(this, 3));
        rvPic.setAdapter(mAdapter);
        rvPic.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.right = DisplayHelper.dp2px(AliUploadActivity.this, 8);
                outRect.bottom = DisplayHelper.dp2px(AliUploadActivity.this, 8);
                if (parent.getChildLayoutPosition(view) % 3 == 0) {
                    outRect.right = 0;
                }
            }
        });
    }

    public void uploadComplete() {

    }

    public AliOssService initOSS(String endpoint, AliUIDisplayer displayer) {

//        移动端是不安全环境，不建议直接使用阿里云主账号ak，sk的方式。建议使用STS方式。具体参
//        https://help.aliyun.com/document_detail/31920.html
//        注意：SDK 提供的 PlainTextAKSKCredentialProvider 只建议在测试环境或者用户可以保证阿里云主账号AK，SK安全的前提下使用。具体使用如下
//        主账户使用方式
//        String AK = "******";
//        String SK = "******";
//        credentialProvider = new PlainTextAKSKCredentialProvider(AK,SK)
//        以下是使用STS Sever方式。
//        如果用STS鉴权模式，推荐使用OSSAuthCredentialProvider方式直接访问鉴权应用服务器，token过期后可以自动更新。
//        详见：https://help.aliyun.com/document_detail/31920.html
//        OSSClient的生命周期和应用程序的生命周期保持一致即可。在应用程序启动时创建一个ossClient，在应用程序结束时销毁即可。

        //使用自己的获取STSToken的类
        OSSCredentialProvider credentialProvider = new OSSAuthCredentialsProvider(Config.STS_SERVER_URL);
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(9); // 最大并发请求书，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider, conf);
        OSSLog.enableLog();
        return new AliOssService(oss, Config.BUCKET_NAME, displayer);

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == Activity.RESULT_OK) {
            finalKeys.clear();
            List<Uri> elements1 = Matisse.obtainResult(data);
            for (int i = 0; i < elements1.size(); i++) {
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Uri element = elements1.get(i);
                Cursor cursor = getContentResolver().query(element,
                        filePathColumn, null, null, null);

                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);

                if (columnIndex != -1) {
                    String mPicturePath = cursor.getString(columnIndex);
                    if (mPicturePath.endsWith(".mp4")) {
                        type = 2;
                        break;
                    } else {
                        type = 1;
                        break;
                    }
                } else {
                    String mPicturePath = Matisse.obtainPathResult(data).get(0);
                    CamerImageBean.getInstance().setImagePath(mPicturePath);
                    if (mPicturePath.endsWith(".mp4")) {
                        type = 2;
                        break;
                    } else {
                        type = 1;
                        break;
                    }
                }
            }

            if (type == 2) {//选择了视频
                mAdapter.setType(type);
                elements.clear();
                elements.addAll(elements1);
                mAdapter.addALLVideo(elements1);
            } else {//选择了照片
                mAdapter.setType(type);
                elements.addAll(elements1);
                mAdapter.addALL(elements1);
            }
        }
    }


    @Override
    public void addPhoto() {
        Matisse.from(AliUploadActivity.this)
                .choose(MimeType.ofAll())
                .countable(true)
                .capture(true)
                .captureStrategy(new CaptureStrategy(true, "cn.dankal.flyaudio.provider.download"))
                .maxSelectablePerMediaType(maxCount, 1)
//                      .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
//                      .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new Glide4Engine())
                .forResult(REQUEST_CODE_CHOOSE);
    }

    @Override
    public void deletePhoto(int pos) {
        elements.remove(pos);
        ToastUtils.showShort("删除成功");
    }

    public static String getImageAbsolutePath(Activity context, Uri imageUri) {
        if (context == null || imageUri == null)
            return null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, imageUri)) {
            if (isExternalStorageDocument(imageUri)) {
                String docId = DocumentsContract.getDocumentId(imageUri);
                String[] split = docId.split(":");
                String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } else if (isDownloadsDocument(imageUri)) {
                String id = DocumentsContract.getDocumentId(imageUri);
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            } else if (isMediaDocument(imageUri)) {
                String docId = DocumentsContract.getDocumentId(imageUri);
                String[] split = docId.split(":");
                String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                String selection = MediaStore.Images.Media._ID + "=?";
                String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        } // MediaStore (and general)
        else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(imageUri))
                return imageUri.getLastPathSegment();
            return getDataColumn(context, imageUri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
            return imageUri.getPath();
        }
        return null;
    }

    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        String column = MediaStore.Images.Media.DATA;
        String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

}
